/**
 * 搜索页面JS文件 - 负责搜索功能的实现
 */

document.addEventListener('DOMContentLoaded', () => {
    // 获取DOM元素
    const searchForm = document.getElementById('search-form');
    const searchInput = document.getElementById('search-input');
    const searchTypeSelect = document.getElementById('search-type');
    const resultsContainer = document.getElementById('search-results');
    const paginationContainer = document.getElementById('pagination');
    const filtersContainer = document.getElementById('search-filters');
    const sortSelect = document.getElementById('sort-select');
    
    // 当前搜索参数
    let currentSearchParams = {
        query: '',
        type: 'all',
        page: 1,
        filters: {},
        sort: 'relevance'
    };
    
    // 初始化页面
    initSearchPage();
    
    /**
     * 初始化搜索页面
     */
    function initSearchPage() {
        // 获取URL参数
        const urlParams = new URLSearchParams(window.location.search);
        
        // 设置初始搜索参数
        currentSearchParams.query = urlParams.get('q') || '';
        currentSearchParams.type = urlParams.get('type') || 'all';
        currentSearchParams.page = parseInt(urlParams.get('page')) || 1;
        currentSearchParams.sort = urlParams.get('sort') || 'relevance';
        
        // 设置表单初始值
        if (searchInput) searchInput.value = currentSearchParams.query;
        if (searchTypeSelect) searchTypeSelect.value = currentSearchParams.type;
        if (sortSelect) sortSelect.value = currentSearchParams.sort;
        
        // 解析过滤器参数
        urlParams.forEach((value, key) => {
            if (key.startsWith('filter_')) {
                const filterName = key.replace('filter_', '');
                currentSearchParams.filters[filterName] = value;
            }
        });
        
        // 如果有查询参数，执行搜索
        if (currentSearchParams.query) {
            performSearch();
        }
        
        // 添加事件监听器
        if (searchForm) {
            searchForm.addEventListener('submit', handleSearchSubmit);
        }
        
        if (sortSelect) {
            sortSelect.addEventListener('change', handleSortChange);
        }
        
        // 初始化过滤器
        initFilters();
    }
    
    /**
     * 初始化过滤器
     */
    function initFilters() {
        if (!filtersContainer) return;
        
        // 根据搜索类型显示不同的过滤器
        let filtersHtml = '';
        
        switch (currentSearchParams.type) {
            case 'news':
                filtersHtml = `
                    <div class="filter-group">
                        <h5>发布日期</h5>
                        <div class="form-check">
                            <input class="form-check-input filter-checkbox" type="checkbox" value="last_day" id="filter-date-last-day" 
                                ${currentSearchParams.filters.date === 'last_day' ? 'checked' : ''}>
                            <label class="form-check-label" for="filter-date-last-day">
                                过去24小时
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input filter-checkbox" type="checkbox" value="last_week" id="filter-date-last-week"
                                ${currentSearchParams.filters.date === 'last_week' ? 'checked' : ''}>
                            <label class="form-check-label" for="filter-date-last-week">
                                过去一周
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input filter-checkbox" type="checkbox" value="last_month" id="filter-date-last-month"
                                ${currentSearchParams.filters.date === 'last_month' ? 'checked' : ''}>
                            <label class="form-check-label" for="filter-date-last-month">
                                过去一个月
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input filter-checkbox" type="checkbox" value="last_year" id="filter-date-last-year"
                                ${currentSearchParams.filters.date === 'last_year' ? 'checked' : ''}>
                            <label class="form-check-label" for="filter-date-last-year">
                                过去一年
                            </label>
                        </div>
                    </div>
                    <div class="filter-group">
                        <h5>新闻来源</h5>
                        <div class="form-check">
                            <input class="form-check-input filter-checkbox" type="checkbox" value="major" id="filter-source-major"
                                ${currentSearchParams.filters.source === 'major' ? 'checked' : ''}>
                            <label class="form-check-label" for="filter-source-major">
                                主流媒体
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input filter-checkbox" type="checkbox" value="tech" id="filter-source-tech"
                                ${currentSearchParams.filters.source === 'tech' ? 'checked' : ''}>
                            <label class="form-check-label" for="filter-source-tech">
                                科技媒体
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input filter-checkbox" type="checkbox" value="blogs" id="filter-source-blogs"
                                ${currentSearchParams.filters.source === 'blogs' ? 'checked' : ''}>
                            <label class="form-check-label" for="filter-source-blogs">
                                博客
                            </label>
                        </div>
                    </div>
                `;
                break;
                
            case 'papers':
                filtersHtml = `
                    <div class="filter-group">
                        <h5>发布日期</h5>
                        <div class="form-check">
                            <input class="form-check-input filter-checkbox" type="checkbox" value="last_month" id="filter-date-last-month"
                                ${currentSearchParams.filters.date === 'last_month' ? 'checked' : ''}>
                            <label class="form-check-label" for="filter-date-last-month">
                                过去一个月
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input filter-checkbox" type="checkbox" value="last_year" id="filter-date-last-year"
                                ${currentSearchParams.filters.date === 'last_year' ? 'checked' : ''}>
                            <label class="form-check-label" for="filter-date-last-year">
                                过去一年
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input filter-checkbox" type="checkbox" value="last_3_years" id="filter-date-last-3-years"
                                ${currentSearchParams.filters.date === 'last_3_years' ? 'checked' : ''}>
                            <label class="form-check-label" for="filter-date-last-3-years">
                                过去三年
                            </label>
                        </div>
                    </div>
                    <div class="filter-group">
                        <h5>论文引用量</h5>
                        <div class="form-check">
                            <input class="form-check-input filter-checkbox" type="checkbox" value="high" id="filter-citations-high"
                                ${currentSearchParams.filters.citations === 'high' ? 'checked' : ''}>
                            <label class="form-check-label" for="filter-citations-high">
                                高引用量 (100+)
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input filter-checkbox" type="checkbox" value="medium" id="filter-citations-medium"
                                ${currentSearchParams.filters.citations === 'medium' ? 'checked' : ''}>
                            <label class="form-check-label" for="filter-citations-medium">
                                中等引用量 (10-99)
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input filter-checkbox" type="checkbox" value="low" id="filter-citations-low"
                                ${currentSearchParams.filters.citations === 'low' ? 'checked' : ''}>
                            <label class="form-check-label" for="filter-citations-low">
                                低引用量 (0-9)
                            </label>
                        </div>
                    </div>
                `;
                break;
                
            case 'companies':
                filtersHtml = `
                    <div class="filter-group">
                        <h5>公司类型</h5>
                        <div class="form-check">
                            <input class="form-check-input filter-checkbox" type="checkbox" value="startup" id="filter-type-startup"
                                ${currentSearchParams.filters.company_type === 'startup' ? 'checked' : ''}>
                            <label class="form-check-label" for="filter-type-startup">
                                初创公司
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input filter-checkbox" type="checkbox" value="enterprise" id="filter-type-enterprise"
                                ${currentSearchParams.filters.company_type === 'enterprise' ? 'checked' : ''}>
                            <label class="form-check-label" for="filter-type-enterprise">
                                大型企业
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input filter-checkbox" type="checkbox" value="research" id="filter-type-research"
                                ${currentSearchParams.filters.company_type === 'research' ? 'checked' : ''}>
                            <label class="form-check-label" for="filter-type-research">
                                研究机构
                            </label>
                        </div>
                    </div>
                    <div class="filter-group">
                        <h5>活跃度</h5>
                        <div class="form-check">
                            <input class="form-check-input filter-checkbox" type="checkbox" value="high" id="filter-activity-high"
                                ${currentSearchParams.filters.activity === 'high' ? 'checked' : ''}>
                            <label class="form-check-label" for="filter-activity-high">
                                高活跃度
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input filter-checkbox" type="checkbox" value="medium" id="filter-activity-medium"
                                ${currentSearchParams.filters.activity === 'medium' ? 'checked' : ''}>
                            <label class="form-check-label" for="filter-activity-medium">
                                中等活跃度
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input filter-checkbox" type="checkbox" value="low" id="filter-activity-low"
                                ${currentSearchParams.filters.activity === 'low' ? 'checked' : ''}>
                            <label class="form-check-label" for="filter-activity-low">
                                低活跃度
                            </label>
                        </div>
                    </div>
                `;
                break;
                
            default:
                // 默认过滤器，适用于所有类型
                filtersHtml = `
                    <div class="filter-group">
                        <h5>发布日期</h5>
                        <div class="form-check">
                            <input class="form-check-input filter-checkbox" type="checkbox" value="last_week" id="filter-date-last-week"
                                ${currentSearchParams.filters.date === 'last_week' ? 'checked' : ''}>
                            <label class="form-check-label" for="filter-date-last-week">
                                过去一周
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input filter-checkbox" type="checkbox" value="last_month" id="filter-date-last-month"
                                ${currentSearchParams.filters.date === 'last_month' ? 'checked' : ''}>
                            <label class="form-check-label" for="filter-date-last-month">
                                过去一个月
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input filter-checkbox" type="checkbox" value="last_year" id="filter-date-last-year"
                                ${currentSearchParams.filters.date === 'last_year' ? 'checked' : ''}>
                            <label class="form-check-label" for="filter-date-last-year">
                                过去一年
                            </label>
                        </div>
                    </div>
                `;
        }
        
        filtersContainer.innerHTML = filtersHtml;
        
        // 为过滤器复选框添加事件监听
        const filterCheckboxes = document.querySelectorAll('.filter-checkbox');
        filterCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', handleFilterChange);
        });
    }
    
    /**
     * 处理搜索表单提交
     * @param {Event} e - 表单提交事件
     */
    function handleSearchSubmit(e) {
        e.preventDefault();
        
        // 更新搜索参数
        currentSearchParams.query = searchInput.value.trim();
        if (searchTypeSelect) {
            currentSearchParams.type = searchTypeSelect.value;
        }
        currentSearchParams.page = 1; // 重置页码
        
        // 更新URL
        updateUrl();
        
        // 执行搜索
        performSearch();
    }
    
    /**
     * 处理排序变更
     */
    function handleSortChange() {
        currentSearchParams.sort = sortSelect.value;
        updateUrl();
        performSearch();
    }
    
    /**
     * 处理过滤器变更
     * @param {Event} e - 复选框变更事件
     */
    function handleFilterChange(e) {
        const checkbox = e.target;
        const filterGroup = checkbox.id.split('-')[1]; // 例如 date, source, citations
        const filterValue = checkbox.value;
        
        // 取消同组其他复选框的选中状态
        const groupCheckboxes = document.querySelectorAll(`[id^="filter-${filterGroup}"]`);
        groupCheckboxes.forEach(cb => {
            if (cb !== checkbox) {
                cb.checked = false;
            }
        });
        
        // 更新过滤器参数
        if (checkbox.checked) {
            currentSearchParams.filters[filterGroup] = filterValue;
        } else {
            delete currentSearchParams.filters[filterGroup];
        }
        
        // 重置页码
        currentSearchParams.page = 1;
        
        // 更新URL
        updateUrl();
        
        // 执行搜索
        performSearch();
    }
    
    /**
     * 执行搜索操作
     */
    async function performSearch() {
        if (!resultsContainer) return;
        
        // 显示加载状态
        App.showLoading(resultsContainer);
        
        try {
            // 准备搜索参数
            const searchParams = {
                query: currentSearchParams.query,
                type: currentSearchParams.type,
                page: currentSearchParams.page,
                sort: currentSearchParams.sort,
                ...currentSearchParams.filters
            };
            
            // 发送API请求
            const data = await App.fetchAPI(App.API_ENDPOINTS.SEARCH, {
                method: 'POST',
                body: JSON.stringify(searchParams)
            });
            
            // 渲染搜索结果
            renderSearchResults(data);
            
            // 渲染分页
            renderPagination(data.total, data.page, data.per_page);
            
        } catch (error) {
            App.showError(resultsContainer, '搜索失败，请稍后重试');
        }
    }
    
    /**
     * 渲染搜索结果
     * @param {Object} data - 搜索结果数据
     */
    function renderSearchResults(data) {
        if (!data || !data.results || data.results.length === 0) {
            resultsContainer.innerHTML = `
                <div class="no-results">
                    <i class="fas fa-search"></i>
                    <h3>未找到相关结果</h3>
                    <p>请尝试使用其他关键词或调整搜索过滤器</p>
                </div>
            `;
            return;
        }
        
        // 创建结果HTML
        let resultsHtml = `
            <div class="search-summary">
                <p>找到 <strong>${data.total}</strong> 个结果 (用时 ${data.search_time.toFixed(2)} 秒)</p>
            </div>
            <div class="search-results-list">
        `;
        
        // 根据结果类型渲染不同的结果卡片
        data.results.forEach(result => {
            const date = App.formatDate(result.date || result.published_date);
            
            switch (result.type) {
                case 'news':
                    // 创建标签HTML
                    let tagsHtml = '';
                    if (result.tags && result.tags.length > 0) {
                        tagsHtml = result.tags.slice(0, 3).map(tag => 
                            `<span class="badge bg-secondary">${tag}</span>`
                        ).join(' ');
                    }
                    
                    resultsHtml += `
                        <div class="result-card">
                            <div class="result-header">
                                <span class="result-type news-type">新闻</span>
                                <span class="result-source">${result.source}</span>
                                <span class="result-date">${date}</span>
                            </div>
                            <h3 class="result-title"><a href="/news/${result.id}">${result.title}</a></h3>
                            <p class="result-summary">${result.summary}</p>
                            <div class="result-tags">${tagsHtml}</div>
                            <div class="result-actions">
                                <a href="${result.url}" target="_blank" class="btn btn-sm btn-outline-primary">阅读原文</a>
                                <a href="/news/${result.id}" class="btn btn-sm btn-link">详情</a>
                            </div>
                        </div>
                    `;
                    break;
                    
                case 'paper':
                    resultsHtml += `
                        <div class="result-card">
                            <div class="result-header">
                                <span class="result-type paper-type">论文</span>
                                <span class="result-date">${date}</span>
                            </div>
                            <h3 class="result-title"><a href="/papers/${result.id}">${result.title}</a></h3>
                            <div class="result-authors">${result.authors.join(', ')}</div>
                            <p class="result-summary">${result.abstract.substring(0, 250)}${result.abstract.length > 250 ? '...' : ''}</p>
                            <div class="result-metrics">
                                <span><i class="fas fa-quote-right"></i> 引用: ${result.citations}</span>
                                <span><i class="fas fa-eye"></i> 浏览: ${result.views}</span>
                            </div>
                            <div class="result-actions">
                                <a href="${result.url}" target="_blank" class="btn btn-sm btn-outline-primary">查看原文</a>
                                <a href="/papers/${result.id}" class="btn btn-sm btn-link">详情</a>
                            </div>
                        </div>
                    `;
                    break;
                    
                case 'company':
                    resultsHtml += `
                        <div class="result-card">
                            <div class="result-header">
                                <span class="result-type company-type">企业</span>
                                <span class="result-company-type">${result.company_type}</span>
                            </div>
                            <h3 class="result-title"><a href="/companies/${result.id}">${result.name}</a></h3>
                            <p class="result-summary">${result.description}</p>
                            <div class="result-activity">
                                <h5>最近活动:</h5>
                                ${result.recent_activity ? 
                                    `<p>${result.recent_activity}</p>` : 
                                    `<p>暂无最近活动</p>`
                                }
                            </div>
                            <div class="result-actions">
                                <a href="/companies/${result.id}" class="btn btn-sm btn-outline-primary">公司详情</a>
                            </div>
                        </div>
                    `;
                    break;
                    
                case 'topic':
                    resultsHtml += `
                        <div class="result-card">
                            <div class="result-header">
                                <span class="result-type topic-type">话题</span>
                            </div>
                            <h3 class="result-title"><a href="/topics/${result.id}">${result.name}</a></h3>
                            <p class="result-summary">${result.description}</p>
                            <div class="topic-stats">
                                <span><i class="fas fa-newspaper"></i> 相关新闻: ${result.news_count}</span>
                                <span><i class="fas fa-file-alt"></i> 相关论文: ${result.papers_count}</span>
                                <span><i class="fas fa-building"></i> 相关企业: ${result.companies_count}</span>
                            </div>
                            <div class="result-actions">
                                <a href="/topics/${result.id}" class="btn btn-sm btn-outline-primary">话题详情</a>
                            </div>
                        </div>
                    `;
                    break;
                    
                default:
                    resultsHtml += `
                        <div class="result-card">
                            <div class="result-header">
                                <span class="result-type">其他</span>
                                <span class="result-date">${date}</span>
                            </div>
                            <h3 class="result-title"><a href="${result.url}">${result.title}</a></h3>
                            <p class="result-summary">${result.summary || result.description}</p>
                        </div>
                    `;
            }
        });
        
        resultsHtml += '</div>';
        
        // 更新结果容器
        resultsContainer.innerHTML = resultsHtml;
    }
    
    /**
     * 渲染分页控件
     * @param {number} total - 总结果数
     * @param {number} currentPage - 当前页码
     * @param {number} perPage - 每页结果数
     */
    function renderPagination(total, currentPage, perPage) {
        if (!paginationContainer) return;
        
        const totalPages = Math.ceil(total / perPage);
        
        if (totalPages <= 1) {
            paginationContainer.innerHTML = '';
            return;
        }
        
        let paginationHtml = '<ul class="pagination justify-content-center">';
        
        // 上一页按钮
        paginationHtml += `
            <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${currentPage - 1}" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            </li>
        `;
        
        // 页码按钮
        const maxVisiblePages = 5;
        let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
        let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
        
        if (endPage - startPage + 1 < maxVisiblePages) {
            startPage = Math.max(1, endPage - maxVisiblePages + 1);
        }
        
        // 第一页按钮
        if (startPage > 1) {
            paginationHtml += `
                <li class="page-item">
                    <a class="page-link" href="#" data-page="1">1</a>
                </li>
            `;
            
            if (startPage > 2) {
                paginationHtml += `
                    <li class="page-item disabled">
                        <a class="page-link" href="#">...</a>
                    </li>
                `;
            }
        }
        
        // 中间页码
        for (let i = startPage; i <= endPage; i++) {
            paginationHtml += `
                <li class="page-item ${i === currentPage ? 'active' : ''}">
                    <a class="page-link" href="#" data-page="${i}">${i}</a>
                </li>
            `;
        }
        
        // 最后页按钮
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                paginationHtml += `
                    <li class="page-item disabled">
                        <a class="page-link" href="#">...</a>
                    </li>
                `;
            }
            
            paginationHtml += `
                <li class="page-item">
                    <a class="page-link" href="#" data-page="${totalPages}">${totalPages}</a>
                </li>
            `;
        }
        
        // 下一页按钮
        paginationHtml += `
            <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${currentPage + 1}" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
        `;
        
        paginationHtml += '</ul>';
        
        // 更新分页容器
        paginationContainer.innerHTML = paginationHtml;
        
        // 为分页链接添加事件监听
        const pageLinks = paginationContainer.querySelectorAll('.page-link');
        pageLinks.forEach(link => {
            link.addEventListener('click', handlePageChange);
        });
    }
    
    /**
     * 处理页码变更
     * @param {Event} e - 点击事件
     */
    function handlePageChange(e) {
        e.preventDefault();
        
        const pageLink = e.currentTarget;
        const page = parseInt(pageLink.dataset.page);
        
        if (isNaN(page) || page === currentSearchParams.page) {
            return;
        }
        
        // 更新当前页码
        currentSearchParams.page = page;
        
        // 更新URL
        updateUrl();
        
        // 执行搜索
        performSearch();
        
        // 滚动到顶部
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }
    
    /**
     * 更新URL参数
     */
    function updateUrl() {
        const urlParams = new URLSearchParams();
        
        // 添加基本参数
        if (currentSearchParams.query) {
            urlParams.set('q', currentSearchParams.query);
        }
        
        if (currentSearchParams.type !== 'all') {
            urlParams.set('type', currentSearchParams.type);
        }
        
        if (currentSearchParams.page > 1) {
            urlParams.set('page', currentSearchParams.page.toString());
        }
        
        if (currentSearchParams.sort !== 'relevance') {
            urlParams.set('sort', currentSearchParams.sort);
        }
        
        // 添加过滤器参数
        Object.entries(currentSearchParams.filters).forEach(([key, value]) => {
            urlParams.set(`filter_${key}`, value);
        });
        
        // 更新URL，不刷新页面
        const newUrl = `${window.location.pathname}?${urlParams.toString()}`;
        history.pushState({ path: newUrl }, '', newUrl);
    }
}); 